<template>
  <div class="addressList">
    <van-nav-bar
      title="地址列表"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      right-text="新增地址"
      @click-right="onClickRight"
    />
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @click-item="clickItem"
      add-button-text="确定"
    />
  </div>
</template>
<script>
import { Toast } from "vant";
import { addressList } from "../common/Api/index.js";
export default {
  data() {
    return {
      chosenAddressId: 1,
      list: [],
      information: JSON.parse(sessionStorage.getItem("information")),
      select: {},
      key: null,
    };
  },
  mounted() {
    if (this.$route.query.key) {
      this.key = this.$route.query.key;
    } else {
      sessionStorage.setItem("active", JSON.stringify("setting"));
    }
    this.addressList1();
  },
  methods: {
    addressList1() {
      addressList(this.information.uid).then((res) => {
        res.forEach((item, index) => {
          this.list.push({
            id: index + 1,
            name: item.username,
            tel: item.phone,
            address: item.address,
            addressDetail: item.detailed,
            uid: item.uId,
          });
        });
        this.select = this.list[0];
      });
    },
    onClickLeft() {
      if (this.key == 1) {
        this.$router.push("/settlement");
      } else {
        this.$router.push("/");
      }
    },
    onAdd() {
      if (this.select == undefined) {
        Toast("请新增地址");
        return;
      } else {
        sessionStorage.setItem("currentContact", JSON.stringify(this.select));
        if (this.key == 1) {
          this.$router.push("/settlement");
        } else {
          this.$router.push("/");
        }
      }
    },
    clickItem(item) {
      this.select = item;
      console.log(this.select);
    },
    onEdit(item, index) {
      Toast("编辑地址:" + index);
    },
    onClickRight() {
      if (this.key == 1) {
        this.$router.push({ path: "/addressEditing", query: { key: 1 } });
      } else {
        this.$router.push("/addressEditing");
      }

      //
    },
  },
};
</script>